class Solution {
public:
    void duplicateZeros(vector<int>& a) {
        int n = a.size();
        int idx = 0;
        int sum = 0;
        for (int i = 0; i < n; i++) {
            if (!a[i])sum += 2;
            else sum++;
            if (sum >= n) {
                idx = i;
                break;
            }
        }
        bool flag = sum > n ? 1 : 0;
        int i = n - 1;
        //cout<<"flag=="<<flag<<endl;
        while (idx >= 0) {
            a[i] = a[idx];
            i--;
            if (!a[idx] && !flag) {
                a[i--] = 0;
            }
            else if (!a[idx] && flag) {
                flag = 0;
            }
            idx--;
        }
        //cout<<"idx=="<<idx<<endl;
    }
};